#include "Unit.h"

CUnit::CUnit() : m_pMeshInst(NULL)
{

}

CUnit::CUnit(IntPoint StartingPoint, CTerrain* pTerrain, CCamera* pCamera, ID3D11Device* pDevice) : m_pCamera(pCamera)
{
	m_pTerrain = pTerrain;
	m_mappos = StartingPoint;
	m_pMeshInst = new CUnitMesh(pDevice);
	m_pMeshInst->LoadMesh("..\\Models\\phoenix_ugv.md2");

	m_WorldPos = m_pTerrain->GetWorldPos(m_mappos);
}

void CUnit::Render()
{
	const float ScaleFactor = 0.01;
	mat4 scaleMatrix = MatrixScale(ScaleFactor,ScaleFactor,ScaleFactor);
	mat4 translateMatrix = TranslateMatrix(m_WorldPos.x, m_WorldPos.y, m_WorldPos.z);

	m_pMeshInst->Render(m_pCamera->GetProjectionMatrix(), m_pCamera->GetViewMatrix(), scaleMatrix, translateMatrix);
}

void CUnit::Update( float deltaTime )
{
	const float speed = 0.5f;
	if (m_bMoving)
	{
		// move unit
		m_movePrc += speed * deltaTime;
		m_movePrc = min(m_movePrc, 1.0f);

		// way point reached
		if (m_movePrc == 1.0f)
		{
			// goal reached
			if (m_activeWP + 1 >= m_path.size())
			{
				m_bMoving = false;
			}
			// next waypoint
			else
			{
				m_activeWP++;
				MoveUnit(m_path[m_activeWP]);
			}			
		
		}

		m_WorldPos = m_lastWP * (1 - m_movePrc) + m_nextWP * m_movePrc;

	}
}

CUnit::~CUnit()
{
	SAFE_DELETE(m_pMeshInst);
}

void CUnit::Goto( IntPoint endPoint )
{
	m_path.clear();
	m_activeWP = 0;

	m_path = m_pTerrain->GetPath(m_mappos, endPoint);

	if (m_path.size() > 0)
	{
		m_bMoving = true;
	}

	MoveUnit(m_path[m_activeWP]);
}

void CUnit::MoveUnit( IntPoint to ) 
{
	m_lastWP = m_pTerrain->GetWorldPos(m_mappos);

	m_mappos = to;
	m_movePrc = 0.0f;

	m_nextWP = m_pTerrain->GetWorldPos(m_mappos);
}